<template>
    <div class="HomeArticle">
        <!-- 文章列表 -->
        <div class="article_head">
            <el-button type="primary" style="margin-left: 10px;" @click="addArticleBtn">添加文章</el-button>
        </div>
        <el-table :data="tableData.slice((admincurrentPage - 1) * adminpage, admincurrentPage * adminpage)"
            style="width: 100%;height: calc(100% - 90px);" :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center', background: '#f0f0f5', color: '#606266' }" border>
            <el-table-column label="序号" width="55">
                <template slot-scope="scope">
                    <span>{{ (admincurrentPage - 1) * adminpage + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="标题" prop="title">
            </el-table-column>
            <el-table-column label="封面">
                <template slot-scope="scope">
                    <el-image style="width: 50px; height: 50px" :src="$url + (scope.row.imageList[0]).url"
                        :preview-src-list="scope.row.bigImg">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column label="内容">
                <template slot-scope="scope">
                    {{ scope.row.content.length > 17 ? scope.row.content.substring(0, 17) + '...' : scope.row.content }}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime">
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="text-align: center;height: 40px;" background @current-change="adminhandleCurrentChange"
            :current-page.sync="admincurrentPage" layout="prev, pager, next" :page-size="adminpage"
            :total="tableData.length">
        </el-pagination>
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
            <el-form :model="ruleForm" status-icon ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="标题" prop="title">
                    <el-input type="text" placeholder="请输入标题" v-model="ruleForm.title" maxlength="30"
                        show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input type="textarea" placeholder="请输入内容" v-model="ruleForm.content" maxlength="2000"
                        show-word-limit>
                    </el-input>
                </el-form-item>
                <el-form-item label="关联美食" prop="goodsId">
                    <el-select v-model="ruleForm.goodsId" placeholder="请选择美食">
                        <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="图片" prop="imageList">
                    <el-upload class="upload-demo" action="" :on-change="handleChange" :on-remove="handleRemove" :limit="9"
                        :file-list="fileList" list-type="picture" :http-request="UploadFile">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="SubmitArticle">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import apiArticle from '@/api/apiArticle'
export default {
    name: 'V2HomeArticle',

    data() {
        return {
            tableData: [],
            admincurrentPage: 1,
            adminpage: 10,
            dialogVisible: false,
            dialogTitle: "添加文章",
            ruleForm: {
                imageList: []
            },
            fileList: [],
            SelectFile: "",
            options: [],
            rowImage: []
        };
    },

    mounted() {

    },
    created() {
        this.getAllArticle()
    },
    methods: {
        getAllArticle() {
            apiArticle.getAllArticle().then(res => {
                if (res.data.length > 0) {
                    res.data.forEach(val => {
                        val.bigImg = val.imageList.map(ele => this.$url + ele.url)
                    })
                }
                this.tableData = res.data
            })
        },
        getGoodsNameAndId() {
            apiArticle.getGoodsNameAndId().then(res => {
                this.options = res.data
            })
        },
        addArticleBtn() {
            this.dialogTitle = "添加文章"
            this.ruleForm.imageList = []
            this.ruleForm = { imageList: [] }
            this.fileList = []
            this.getGoodsNameAndId()
            this.dialogVisible = true
        },
        // 添加文章
        addArticle() {
            this.ruleForm.imageList = JSON.stringify(this.ruleForm.imageList)
            if (this.rowImage.length > 0) {
                apiArticle.UpdateArticle(this.ruleForm).then(res => {
                    this.ruleForm = { imageList: [] }
                    this.fileList = []
                    this.dialogVisible = false
                    this.$message.success("修改成功！")
                    setTimeout(() => {
                        this.getAllArticle()
                    }, 500)
                })
            } else {
                apiArticle.addArticle(this.ruleForm).then(res => {
                    this.ruleForm = { imageList: [] }
                    this.fileList = []
                    this.dialogVisible = false
                    this.$message.success("添加成功！")
                    setTimeout(() => {
                        this.getAllArticle()
                    }, 500)
                })
            }
        },
        SubmitArticle() {
            if (!this.ruleForm.title || !this.ruleForm.content || !this.ruleForm.goodsId || this.ruleForm.imageList.length == 0) {
                this.$message.warning("请检查输入内容！")
            } else {
                this.addArticle()
            }
        },
        handleEdit(index, row) {
            this.dialogTitle = "修改文章"
            let list = []
            this.rowImage = JSON.parse(JSON.stringify(row.imageList))
            this.rowImage.forEach(val => {
                list.push({ name: val.name, url: this.$url + val.url })
            })
            this.fileList = list
            this.ruleForm = JSON.parse(JSON.stringify(row))
            this.ruleForm.imageList = row.imageList
            this.getGoodsNameAndId()
            this.dialogVisible = true
        },
        UploadFile() {
            let formData = new FormData();
            formData.append('file', this.SelectFile.raw);
            apiArticle.UploadFile(formData).then(res => {
                this.ruleForm.imageList.push({ name: this.SelectFile.name, url: '/static/' + res.data.url })
            })
        },
        handleChange(file, fileList) {
            this.SelectFile = file
        },
        handleDelete(index, row) {
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                apiArticle.deleteArticle({ id: row.id }).then(res => {
                    this.$message.success('删除成功')
                    setTimeout(() => {
                        this.getAllArticle()
                    }, 500)
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        adminhandleCurrentChange(val) {
            this.admincurrentPage = val
        },
        handleClose(done) {
            this.rowImage = []
            done()
        },
        handleRemove(file, fileList) {
            this.ruleForm.imageList = this.ruleForm.imageList.filter(val => {
                return !file.url.includes(val.url)
            })
        }
    },
};
</script>

<style lang="less" scoped>
.HomeArticle {
    width: 100%;
    height: 100%;

    .article_head {
        width: 100%;
        height: 50px;
        line-height: 50px;
    }
}

@media screen and (max-width: 550px) {
    /deep/ .el-dialog {
        width: 90% !important;
    }
}
</style>